package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;

    /**
     * 注册成功初始化用户信息
     * @param userId
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            key = {MqConst.ROUTING_USER_REGISTER}
    ))
    public void addUserAccount(Long userId, Message message, Channel channel) {
        //业务处理
        try {
            if(null != userId){
                log.info("注册成功初始化用户账户信息:{}",userId);
                userAccountService.addUserAccount(userId);
            }
        } catch (Exception e) {
            //可以采用redis进行重试
            /*
            if(count>=3){
            落表数据库,存储信息
            }
             */
            //  如果网络抖动，可以调用内置的重试方法      第二个false批量拒绝，第三个true将消息重新入队，等待后续重试
            //channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            log.error(e.getMessage(),e);
        }
        //手动应答
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
